<?php

namespace app\index\controller;
use think\Controller;
use  think\Request;
use think\Db;
use think\Cookie;

class Base extends Controller
{


    public function _initialize()
    {

        $request = Request::instance();
        $mod =  $request->module();
        $con = $request->controller();
        $act= $request->action();
        if($mod=='index'&&$con=='Index'){
            if (!$this->ismobile()) {
                if($act=='article_detail'){
                    $arr2=explode("/", $request->path());
                    $thisid=$arr2[count($arr2)-1];
                    $this->redirect('web/article/index',array('id'=>$thisid));
                }
                if($act=='essay_detail'){
                    $arr2=explode("/", $request->path());
                    $thisid=$arr2[count($arr2)-1];
                    $this->redirect('web/article/essay_detail',array('id'=>$thisid));
                }
                if($act=='debatae_detail'){
                    $arr2=explode("/", $request->path());
                    $thisid=$arr2[count($arr2)-1];
                    $this->redirect('web/article/debatae_detail',array('id'=>$thisid));
                }
            }
        }


        if($mod=='index'&&$con=='User'&&$act=='user_info'){
            if (!$this->ismobile()) {
                    $arr2=explode("/", $request->path());
                    $thisid=$arr2[count($arr2)-1];
                    $this->redirect('web/user/center',array('user_id'=>$thisid));

            }
        }




        if (!$this->ismobile()) {
            //header("Location: http://www.shuren100.com/web/index/index.html");
            $this->redirect('web/index/index');
        }

        $user_id = session('user_id');

        if(empty($user_id)){
            if($this->is_weixin()){
                $shuren_open_id = session('shuren_open_id');
//                echo $shuren_open_id;
                if (!empty($shuren_open_id)) {

                    $user_info = DB::name('member')->where('shuren_open_id', $shuren_open_id)->find();
                    if ($user_info) {
                        session('user_id', $user_info['id']);
                        session('instit_id', $user_info['instit_id']);
                        session('group_id', $user_info['group_id']);
                    } else {
                        session('shuren_open_id', $shuren_open_id);
                    }
                }else{
                    $wechat_instit = Db::name('wechat')->where('instit_id', 1)->order('id asc')->find();

//                    print_R($wechat_instit);
                    $shuren_open_id = $this->get_shuren_openid($wechat_instit['appid'], $wechat_instit['appsecret']);
                }

            }
        }

       //$this->is_session();
    }


    public function text(){
       $info = DB::name('member')->where('account','18657240931')->find();
        print_R($info);
    }

   public function ismobile() {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
            return true;

        //此条摘自TPM智能切换模板引擎，适合TPM开发
        if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
            return true;
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
        //判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array(
                'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
            );
            //从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        //协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }





//if(ismobile()){
//    //定义title的公众部分
//header("Location: http://m.enkiorder.com/");
//exit;
//    // 定义应用目录
//    //define('APP_PATH','./Mobile/');
//}else
//    {
//        // 定义应用目录
//        define('APP_PATH','./Application/');
//    }
//


    public  function  get_ad($id){
        $ad_position =  Db::name('ad_position')->where('id',$id)->find();
        $map['closed'] = 0;
        $map['status'] = 1;
        $ad =  Db::name('ad')->where($map)->where('ad_position_id',$id)->order('id desc')->select();
        $result['type'] = $ad_position['type'];
        if($ad_position['type']==0){
            $result['ad'] = $ad[0];
        }else{
            $result['ad'] = $ad;
        }
        return $result;
    }

    public  function  read_article($article_id){
        $view =  Db::name('article')->field('views')->where('id',$article_id)->find();
        if($view){
            $new = $view['views']+1;
            Db::name('article')->where('id',$article_id)->setField('views',$new);
        }
        $map =array(
            'article_id'=>$article_id,
            'user_id'=>session('user_id'),
            'addtime'=>time()
        );
        Db::name('article_read_log')->insert($map);

    }


    public function  replaces($content){
        $new = array(
            '1'=>'汗',
            '2'=>'白眼',
            '3'=>'鄙视',
            '4'=>'打',
            '5'=>'大哭',
            '6'=>'鼓掌',
            '7'=>'奸笑',
            '8'=>'惊吓',
            '9'=>'纠结',
            '10'=>'可爱',
            '11'=>'可怜',
            '12'=>'酷',
            '13'=>'脸红',
            '14'=>'骂人',
            '15'=>'亲亲',
            '16'=>'傻',
            '17'=>'调皮',
            '18'=>'偷笑',
            '19'=>'委屈',
            '20'=>'无语',
            '21'=>'晕',
            '22'=>'抠鼻');

            for($i=1;$i<=22;$i++){
            $str1 = '<img src="/static/emoji/img/'.$i.'.gif">';
            $str2 = '['.$new[$i].']';
                $content =  str_replace($str2,$str1,$content);
            }

        return $content;


    }

    public function is_session(){
        $user_id =  Cookie::get('user_id');
        if($user_id){
            $info = Db::name('member')->where('id',$user_id)->find();
            $s_user_id = session('user_id');
            $s_group_id = session('group_id');
            $s_instit_id = session('instit_id');
            if(empty($s_user_id)||empty($s_group_id)||empty($s_instit_id)){
                session('user_id',$info['id']);
                session('instit_id',$info['instit_id']);
                session('group_id',$info['group_id']);
            }
        }
    }


    public function get_config_v($v){
        $info= Db::name('config')->where('name',$v)->find();
        if($info){
            return $info['value'];
        }else
            return '';
    }


    public function user_signs($user_id,$every_sign_integral,$sign_cycle)
    {

        $day = strtotime(date('Y-m-d'));
        $last_sign = Db::name('sign_log')->where(['user_id' => $user_id, 'type' => 'sign'])->order('id desc')->find();


        if ($last_sign['sign_time'] == $day) {
            $res['code'] = -2;
            return $res;
        }

        $member = Db::name('member')->field('integral,integral_num')->where('id', $user_id)->find();
        $cha = $day - $last_sign['sign_time'];
        if ($cha == 86400) {
            $thisintegral = $member['integral_num'] * $every_sign_integral;
            $thisintegral_num = $member['integral_num'] + 1;
            if ($thisintegral_num > $sign_cycle) {
                $thisintegral_num = 1;
            }


        } else {
            $thisintegral = $member['integral_num'] * 1;
            $thisintegral_num = 1;
        }

        $data = array(
            'integral' => $thisintegral + $member['integral'],
            'integral_num' => $thisintegral_num,
        );

        $result = Db::name('member')->where('id', $user_id)->update($data);

        $datas = array(
            'user_id' => $user_id,
            'sign_time' => $day,
            'integral' => $thisintegral,
            'add_time' => time(),
            'type' => 'sign'
        );
        Db::name('sign_log')->insert($datas);


        if ($result) {
            $res['code'] = 1;
            $res['integral'] = $thisintegral;
        }

        return $res;
    }


//    public function get_openid($appid,$appsecret){
//        $referer = input('get.referer') ? input('get.referer') : "0";
//        if ($referer == "0") {
//            // $last_url = "http://" . $_SERVER["HTTP_HOST"];
//
//            $url = $_SERVER['SERVER_NAME'];
//            $last_url = "http://pc.shuren100.com/index/index/index";
//            $last_url = urlencode($last_url);
//        } else {
//            $last_url =input('get.referer');
//        }
//        $wechat_url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=" . $last_url . "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//
//        $code = input('code');
//        if($code){
//            $access_tokens = $this->get_web_access_token($code,$appid,$appsecret);
//            session('open_id',$access_tokens['openid']);
////            if($access_tokens['openid']){
////                Db::name('member')->where('id',session('user_id'))->update(['open_id'=>$access_tokens['openid']]);
////            }
//        }else{
//            header("Location: " . $wechat_url . "\n");
//        }
//
//    }

    public function get_shuren_openid($appid,$appsecret){
        $referer = input('get.referer') ? input('get.referer') : "0";
        if ($referer == "0") {
            // $last_url = "http://" . $_SERVER["HTTP_HOST"];
            $last_url =  'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];



            $last_url = urlencode($last_url);
        } else {
            $last_url =input('get.referer');
        }
        $wechat_url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=" . $last_url . "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

        $code = input('code');
        if($code){
            //echo $code."|".$appid."|".$appsecret;
            $access_tokens = $this->get_web_access_token($code,$appid,$appsecret);
            session('shuren_open_id',$access_tokens['openid']);
           // return $access_tokens['openid'];
//            if($access_tokens['openid']){
//                Db::name('member')->where('id',session('user_id'))->update(['open_id'=>$access_tokens['openid']]);
//            }
        }else{
            header("Location: " . $wechat_url . "\n");
        }

    }

    public function get_web_access_token($code,$appid,$appsecret)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=" . $code . "&grant_type=authorization_code";
        $data = json_decode(file_get_contents($url), true);
        return $data;
    }

    public function is_weixin(){
			return false;
        if ( strpos($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') !== false ) {

            return true;

        }

        return false;

    }

}